<?php

namespace Home\Logic;

use Lib\Logic\WxcurlLogic;

class WxComponentLogic{
    
    private $wxCurlLogic;
    private $wxappId;
    
    public function __construct(){
        $this->wxCurlLogic = new WxcurlLogic();
        $this->wxappId = C("WX_APPID");
    }
    
    /**
     * 获取第三方平台component_access_token
     */
    public function getComponentAccessToken(){
        $WxComponentAccessModel = M("WxComponentAccessToken", 'shop_', 'DB_CONFIG2');
        $wxComponentAccessData = $WxComponentAccessModel->order('id desc')->find();
        if ($wxComponentAccessData){
            return $wxComponentAccessData;
        } else{
            return false;
        }
    }
    
    /**
     * 获取预授权码pre_auth_code
     * 预授权码用于公众号授权时的第三方平台方安全验证。
     */
    public function getPreAuthCode(){
        //通过数据库获取微信令牌以获取预授权码
        $wxComponentData = $this->getComponentAccessToken();
        if (!$wxComponentData){
            return false;
        }
        $postData['component_appid'] = $this->wxappId;
        $postData = json_encode($postData);
        
        $this->wxCurlLogic->curlUrl = "https://api.weixin.qq.com/cgi-bin/component/api_create_preauthcode?component_access_token=".$wxComponentData['component_access_token'];
        $this->wxCurlLogic->curlPost = true;
        $this->wxCurlLogic->curlData = $postData;
        $result = $this->wxCurlLogic->wx_curl_exec();
        
        return $result;
    }
    
}

?>